package cayte.xiami.in;

import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import cayte.xiami.in.broadcast.CheckinBroadcastReceiver;
import cayte.xiami.in.helper.CrashHelper;
import cayte.xiami.in.service.CheckinService;
import cayte.xiami.in.service.CheckinServiceAIDL;

public class CheckinApp extends Application {

	public CheckinServiceAIDL aidlService;
	public ServiceConnection aidlConnection;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

		D.e("======== Application Start ========");

		CrashHelper.instance().init(this);
		Thread.setDefaultUncaughtExceptionHandler(CrashHelper.instance());

		aidlConnection = new ServiceConnection() {
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				// TODO Auto-generated method stub
				aidlService = CheckinServiceAIDL.Stub.asInterface(service);
			}

			@Override
			public void onServiceDisconnected(ComponentName name) {
				// TODO Auto-generated method stub
				aidlService = null;
			}
		};

		startCheckinService();

		CheckinBroadcastReceiver checkinReceiver = new CheckinBroadcastReceiver();
		IntentFilter intentFilter = new IntentFilter();
		for (String a : checkinReceiver.actionList) {
			intentFilter.addAction(a);
		}
		registerReceiver(checkinReceiver, intentFilter);

	}

	public void startCheckinService() {
		// TODO Auto-generated method stub
		Bundle args = new Bundle();
		Intent intent = new Intent(this, CheckinService.class);
		intent.putExtras(args);
		bindService(intent, aidlConnection, Context.BIND_AUTO_CREATE);
		startService(intent);
	}

	public void stopCheckinService() {
		// TODO Auto-generated method stub
		Bundle args = new Bundle();
		Intent intent = new Intent(this, CheckinService.class);
		intent.putExtras(args);
		unbindService(aidlConnection);
		stopService(intent);
	}

}
